package com.zlsy.thread.lock;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhouliang
 * @date 2020/9/8 20:39
 */
public class ConditionDemo2 {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public static void main(String[] args) {
        ConditionDemo2 demo = new ConditionDemo2();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    demo.m2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        //不能把m1写到前面，写到前面的话m1执行了阻塞 主线程都阻塞了 不能执行唤醒的动作
        demo.m1();
    }

    void m1() {
        lock.lock();
        try {
            System.out.println("条件不满足，开始等待！");
            condition.await();
            System.out.println("条件满足了，开始执行！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void m2() {
        lock.lock();
        try {
            System.out.println("准备工作完成，开始唤醒其他的线程");
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
}
